package controller

import (
	"class-project/model/mysql"
	"class-project/request"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func UserLogin(c *gin.Context) {
	var userLogin request.UserLogin
	if err := c.ShouldBindJSON(&userLogin); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "服务器内部错误",
			"err": err.Error(),
		})
		return
	}
	data := mysql.User{Username: userLogin.Username}
	err := data.Login(userLogin.Username)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "登录失败",
			"err": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":   "登录成功",
		"token": data,
	})
}

func ClassCreate(c *gin.Context) {
	var classCreate request.ClassCreate
	if err := c.ShouldBindJSON(&classCreate); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "服务器内部错误",
			"err": err.Error(),
		})
		return
	}
	data := mysql.Class{
		Name:  classCreate.Name,
		Price: classCreate.Price,
		Num:   classCreate.Num,
	}
	err := data.Create()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "添加失败",
			"err": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "添加成功",
		"data": data,
	})
}

// 课程列表

func ClassList(c *gin.Context) {
	var classList request.ClassList
	if err := c.ShouldBindJSON(&classList); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "服务器内部错误",
			"err": err.Error(),
		})
		return
	}

	data := mysql.Class{
		Name:  classList.Name,
		Price: classList.Price,
		Num:   classList.Num,
	}
	list, err := data.List()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "查询失败",
			"err": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "查询成功",
		"list": list,
	})
}

// 联查

func Search(c *gin.Context) {
	data := mysql.Class{}
	searCh, err := data.SearCh()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "查询失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":    "查询成功",
		"search": searCh,
	})
}

func Sous(c *gin.Context) {
	var userSous request.UserSous
	if err := c.ShouldBindJSON(&userSous); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "服务器内部错误",
			"err": err.Error(),
		})
		return
	}
	username := c.PostForm("username")
	data := mysql.User{Username: username}
	err := data.Sous(data.Username)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "搜索失败",
			"err": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "搜索成功",
		"data": data,
		"time": time.DateTime,
	})
}
